package ifi.p17.thai_cisse;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.*;
import java.util.*;
import javax.swing.*;

import static ifi.p17.thai_cisse.utils.isPhoneNumberValid;
import static ifi.p17.thai_cisse.utils.getFilename;

/**
 * GUI pour affiche les form
 */
public class Carnet {

    private static ResourceBundle resCarnetAdresse = ResourceBundle.getBundle("carnet_adresse", new UTF8Control());
    private static final Insets insets = new Insets(0, 0, 0, 0);

    TextHandler handler = new TextHandler();
    Toolkit kit = Toolkit.getDefaultToolkit();
    Dimension screenSize = kit.getScreenSize();
    int screenHeight = screenSize.height, screenWidth = screenSize.width;

    JFrame frame, addFrame, searchFrame, searchPersonFrame;
    JMenuBar menubar;
    JMenu menuFichier, menuEditer, menuChercher, menuAider;
    JMenuItem menuItemOpen, menuItemSave, menuItemSaveAs, menuItemExit, menuItemAdd, menuItemEdit, menuItemDetele, menuItemEditPerson, menuItemSearch, menuItemAbout;
    JScrollPane scrollPaneAll, scrollPaneSearch;
    JTabbedPane tabAllContact;
    JTextField txtNom, txtNumeroDeTelephone, txtAdresseDeTravail, txtAdresseDeDomicile, txtSearchNom, txtSearchPersonNom;
    JButton btnAdd = new JButton(resCarnetAdresse.getString("BUTTON.Ajouter"));
    JButton btnOK = new JButton(resCarnetAdresse.getString("BUTTON.OK"));
    JButton btnCancel = new JButton(resCarnetAdresse.getString("BUTTON.Annuler"));
    JButton btnSearch = new JButton(resCarnetAdresse.getString("BUTTON.Search"));
    JButton btnSearchCancel = new JButton(resCarnetAdresse.getString("BUTTON.Annuler"));
    JButton btnSearchPerson = new JButton(resCarnetAdresse.getString("BUTTON.Search"));
    JButton btnSearchEdit = new JButton(resCarnetAdresse.getString("MENU.Modifier"));
    JButton btnSearchDetele = new JButton(resCarnetAdresse.getString("MENU.Supprimer"));

    JTable carnetTable, searchTable;
    CarnetTableModel carnetTableModel, searchTableModel;

    int editedRow, startSelection = 0;
    String filePath = null;

    // 	Default Contructor
    Carnet() {
        frame = new JFrame(resCarnetAdresse.getString("TITLE"));
        frame.setSize(960, 450);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(screenWidth / 8, screenHeight / 6);
        addMenubar();
        initTableContact();
        addNewPersonForm();
        searchForm();
        searchPersonForm();
        frame.setVisible(true);
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public void initTableContact() {
        tabAllContact = new JTabbedPane();

        carnetTableModel = new CarnetTableModel();
        carnetTable = new JTable(carnetTableModel);
        scrollPaneAll = new JScrollPane(carnetTable);
        carnetTable.setPreferredScrollableViewportSize(new Dimension(930, 360));

        searchTableModel = new CarnetTableModel();
        searchTable = new JTable(searchTableModel);
        scrollPaneSearch = new JScrollPane(searchTable);
        carnetTable.setPreferredScrollableViewportSize(new Dimension(930, 360));

        tabAllContact.addTab(resCarnetAdresse.getString("TAB_ALL"), scrollPaneAll);
        tabAllContact.setMnemonicAt(0, KeyEvent.VK_1);
        carnetTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        searchTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        frame.getContentPane().add(tabAllContact, BorderLayout.CENTER);
    }

    public void addMenubar() {

        menubar = new JMenuBar();
//----------------------- Fichier Menu ----------------------
        menuFichier = new JMenu(resCarnetAdresse.getString("MENU.Fichier"));

        menuItemOpen = new JMenuItem(resCarnetAdresse.getString("MENU.Ouvert_carnet_adresse"));
        menuFichier.add(menuItemOpen);
        menuItemOpen.addActionListener(handler);

        menuItemSave = new JMenuItem(resCarnetAdresse.getString("MENU.Enregistrer_carnet_adresse"));
        menuFichier.add(menuItemSave);
        menuItemSave.addActionListener(handler);

        menuItemSaveAs = new JMenuItem(resCarnetAdresse.getString("MENU.Enregistrer_as_carnet_adresse"));
        menuFichier.add(menuItemSaveAs);
        menuItemSaveAs.addActionListener(handler);

        menuFichier.addSeparator();

        menuItemExit = new JMenuItem(resCarnetAdresse.getString("MENU.Sortie"));
        menuFichier.add(menuItemExit);
        menuItemExit.addActionListener(handler);

        menubar.add(menuFichier);
//------------------------ Edit ---------------------------
        menuEditer = new JMenu(resCarnetAdresse.getString("MENU.Editer"));

        menuItemAdd = new JMenuItem(resCarnetAdresse.getString("MENU.Creer_carnet"));
        menuEditer.add(menuItemAdd);
        menuItemAdd.addActionListener(handler);

        menuItemEdit = new JMenuItem(resCarnetAdresse.getString("MENU.Modifier"));
        menuEditer.add(menuItemEdit);
        menuItemEdit.addActionListener(handler);

        menuItemDetele = new JMenuItem(resCarnetAdresse.getString("MENU.Supprimer"));
        menuEditer.add(menuItemDetele);
        menuItemDetele.addActionListener(handler);

        menuItemEditPerson = new JMenuItem(resCarnetAdresse.getString("MENU.Modifier_carnet"));
        menuEditer.add(menuItemEditPerson);
        menuItemEditPerson.addActionListener(handler);

        enableEditDeleteAction(false);

        menubar.add(menuEditer);
//------------------------Chercher menu --------------------
        menuChercher = new JMenu(resCarnetAdresse.getString("MENU.Chercher"));

        menuItemSearch = new JMenuItem(resCarnetAdresse.getString("MENU.Chercher_carnet"));
        menuChercher.add(menuItemSearch);
        menuItemSearch.addActionListener(handler);

        menubar.add(menuChercher);
//---------------------- Aider menu ------------------------
        menuAider = new JMenu(resCarnetAdresse.getString("MENU.Aider"));

        menuItemAbout = new JMenuItem(resCarnetAdresse.getString("MENU.About"));
        menuAider.add(menuItemAbout);
        menuItemAbout.addActionListener(handler);

        menubar.add(menuAider);
        frame.setJMenuBar(menubar);
    }

    public void addNewPersonForm() {
        addFrame = new JFrame(resCarnetAdresse.getString("MENU.Creer_carnet"));
        addFrame.setSize(450, 200);
        addFrame.setResizable(false);
        addFrame.setLocation(screenWidth / 3, 2 * screenHeight / 7);

        JLabel lblNom = new JLabel(carnetTableModel.TEXT_NOM);
        JLabel lblNumeroDeTelephone = new JLabel(carnetTableModel.TEXT_NUMERO_DE_TELEPHONE);
        JLabel lblAdresseDeTravail = new JLabel(carnetTableModel.TEXT_ADRESSE_DE_TRAVAIL);
        JLabel lblAdresseDeDomicile = new JLabel(carnetTableModel.TEXT_ADRESSE_DE_DOMICILE);

        txtNom = new JTextField(20);
        txtNumeroDeTelephone = new JTextField(20);
        txtAdresseDeTravail = new JTextField(20);
        txtAdresseDeDomicile = new JTextField(20);

        JPanel topPanel = new JPanel();
        JPanel centerPanel = new JPanel();
        JPanel bottomPane = new JPanel();
        JPanel leftPane = new JPanel();
        JPanel rightPane = new JPanel();

        centerPanel.setLayout(new GridBagLayout());

        centerPanel.add(lblNom);
        addComponent(centerPanel, lblNom, 0, 0, 1, 1);
        centerPanel.add(txtNom);
        addComponent(centerPanel, txtNom, 1, 0, 1, 1);

        centerPanel.add(lblNumeroDeTelephone);
        addComponent(centerPanel, lblNumeroDeTelephone, 0, 2, 1, 1);
        centerPanel.add(txtNumeroDeTelephone);
        addComponent(centerPanel, txtNumeroDeTelephone, 1, 2, 1, 1);

        centerPanel.add(lblAdresseDeTravail);
        addComponent(centerPanel, lblAdresseDeTravail, 0, 4, 1, 1);
        centerPanel.add(txtAdresseDeTravail);
        addComponent(centerPanel, txtAdresseDeTravail, 1, 4, 1, 1);

        centerPanel.add(lblAdresseDeDomicile);
        addComponent(centerPanel, lblAdresseDeDomicile, 0, 6, 1, 1);
        centerPanel.add(txtAdresseDeDomicile);
        addComponent(centerPanel, txtAdresseDeDomicile, 1, 6, 1, 1);

        bottomPane.add(btnAdd);
        bottomPane.add(btnOK);
        bottomPane.add(btnCancel);

        btnAdd.addActionListener(handler);
        btnOK.addActionListener(handler);
        btnCancel.addActionListener(handler);

        txtNom.setFocusable(true);
        btnOK.setVisible(false);

        addFrame.getContentPane().add(topPanel, BorderLayout.NORTH);
        addFrame.getContentPane().add(bottomPane, BorderLayout.SOUTH);
        addFrame.getContentPane().add(centerPanel, BorderLayout.CENTER);
        addFrame.getContentPane().add(leftPane, BorderLayout.WEST);
        addFrame.getContentPane().add(rightPane, BorderLayout.EAST);
        addFrame.setVisible(false);
    }

    public void searchForm() {
        searchFrame = new JFrame(resCarnetAdresse.getString("MENU.Chercher"));
        searchFrame.setSize(340, 125);
        searchFrame.setResizable(false);
        searchFrame.setLocation(screenWidth / 3, 2 * screenHeight / 7);

        JLabel lblNom = new JLabel(carnetTableModel.TEXT_NOM);
        JLabel lblSubject = new JLabel(resCarnetAdresse.getString("LABEL_CHERCHER"));

        txtSearchNom = new JTextField(20);

        btnSearch.addActionListener(handler);
        btnSearchCancel.addActionListener(handler);

        JPanel topPanel = new JPanel();
        JPanel centerPanel = new JPanel();
        JPanel bottomPane = new JPanel();
        JPanel leftPane = new JPanel();
        JPanel rightPane = new JPanel();

        centerPanel.setLayout(new GridBagLayout());

        topPanel.add(lblSubject);

        centerPanel.add(lblNom);
        addComponent(centerPanel, lblNom, 0, 0, 1, 1);
        centerPanel.add(txtSearchNom);
        addComponent(centerPanel, txtSearchNom, 1, 0, 1, 1);

        bottomPane.add(btnSearch);
        bottomPane.add(btnSearchCancel);
        txtSearchNom.setFocusable(true);

        searchFrame.getContentPane().add(topPanel, BorderLayout.NORTH);
        searchFrame.getContentPane().add(bottomPane, BorderLayout.SOUTH);
        searchFrame.getContentPane().add(centerPanel, BorderLayout.CENTER);
        searchFrame.getContentPane().add(leftPane, BorderLayout.WEST);
        searchFrame.getContentPane().add(rightPane, BorderLayout.EAST);
        searchFrame.setVisible(false);
    }

    public void searchPersonForm() {
        searchPersonFrame = new JFrame(resCarnetAdresse.getString("MENU.Chercher"));
        searchPersonFrame.setSize(340, 125);
        searchPersonFrame.setResizable(false);
        searchPersonFrame.setLocation(screenWidth / 3, 2 * screenHeight / 7);

        JLabel lblNom = new JLabel(carnetTableModel.TEXT_NOM);
        JLabel lblSubject = new JLabel(resCarnetAdresse.getString("LABEL_CHERCHER"));

        txtSearchPersonNom = new JTextField(20);

        btnSearchPerson.addActionListener(handler);
        btnSearchEdit.addActionListener(handler);
        btnSearchDetele.addActionListener(handler);

        JPanel topPanel = new JPanel();
        JPanel centerPanel = new JPanel();
        JPanel bottomPane = new JPanel();
        JPanel leftPane = new JPanel();
        JPanel rightPane = new JPanel();

        centerPanel.setLayout(new GridBagLayout());

        topPanel.add(lblSubject);

        centerPanel.add(lblNom);
        addComponent(centerPanel, lblNom, 0, 0, 1, 1);
        centerPanel.add(txtSearchPersonNom);
        addComponent(centerPanel, txtSearchPersonNom, 1, 0, 1, 1);

        bottomPane.add(btnSearchPerson);
        bottomPane.add(btnSearchEdit);
        bottomPane.add(btnSearchDetele);
        txtSearchPersonNom.setFocusable(true);

        searchPersonFrame.getContentPane().add(topPanel, BorderLayout.NORTH);
        searchPersonFrame.getContentPane().add(bottomPane, BorderLayout.SOUTH);
        searchPersonFrame.getContentPane().add(centerPanel, BorderLayout.CENTER);
        searchPersonFrame.getContentPane().add(leftPane, BorderLayout.WEST);
        searchPersonFrame.getContentPane().add(rightPane, BorderLayout.EAST);
        searchPersonFrame.setVisible(false);
    }

    public static void main(String[] args) {
        Carnet carnet = new Carnet();
    }

    private static void addComponent(Container container, Component component,
                                     int gridx, int gridy, int gridwidth, int gridheight) {
        GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
                gridwidth, gridheight, 1.0, 1.0, GridBagConstraints.CENTER,
                GridBagConstraints.BOTH, insets, 0, 0);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        container.add(component, gbc);
    }

    public Personne getPersoneDataFromTextField() {
        Personne personne = new Personne(txtNom.getText(),
                txtNumeroDeTelephone.getText(),
                txtAdresseDeTravail.getText(),
                txtAdresseDeDomicile.getText());
        return personne;
    }

    public void resetTextField() {
        txtNom.setText("");
        txtNumeroDeTelephone.setText("");
        txtAdresseDeTravail.setText("");
        txtAdresseDeDomicile.setText("");
        txtNom.setFocusable(true);
    }

    public void showEditCarte(int selectedRow) {
        editedRow = selectedRow;
        txtNom.setText(carnetTableModel.getValueAt(selectedRow, 0).toString());
        txtNumeroDeTelephone.setText(carnetTableModel.getValueAt(selectedRow, 1).toString());
        txtAdresseDeTravail.setText(carnetTableModel.getValueAt(selectedRow, 2).toString());
        txtAdresseDeDomicile.setText(carnetTableModel.getValueAt(selectedRow, 3).toString());
        btnAdd.setVisible(false);
        btnOK.setVisible(true);
    }

    public boolean validateForm() {
        if ((txtNom.getText().trim().length() == 0) || (txtNumeroDeTelephone.getText().trim().length() == 0) || (txtAdresseDeTravail.getText().trim().length() == 0) || (txtAdresseDeDomicile.getText().trim().length() == 0)) {
            JOptionPane.showMessageDialog(
                    addFrame,
                    resCarnetAdresse.getString("ERRORS.EMPTY"),
                    resCarnetAdresse.getString("TITLE_ERRORS"),
                    JOptionPane.INFORMATION_MESSAGE);
            return false;
        }
        if (!isPhoneNumberValid(txtNumeroDeTelephone.getText())) {
            JOptionPane.showMessageDialog(
                    addFrame,
                    resCarnetAdresse.getString("ERRORS.TELEPHONE_NUMBER"),
                    resCarnetAdresse.getString("TITLE_ERRORS"),
                    JOptionPane.INFORMATION_MESSAGE);
            return false;
        }
        return true;
    }

    public void enableEditDeleteAction(boolean status) {
        menuItemEdit.setEnabled(status);
        menuItemDetele.setEnabled(status);
        menuItemEditPerson.setEnabled(status);
    }

    /**
     * Travail avec fichier
     * Ovrir une existe fichier de carnet
     */
    public boolean openAddressBook() {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        chooser.setMultiSelectionEnabled(false);
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.showOpenDialog(frame);

        FileInputStream bfin = null;
        DataInputStream in;
        BufferedReader br;
        try {
            filePath = chooser.getSelectedFile().getPath();
        } catch (Exception ex) {
        }

        try {
            if (filePath.endsWith(".carnet")) {
                bfin = new FileInputStream(filePath);
            } else {
                JOptionPane.showMessageDialog(
                        addFrame,
                        resCarnetAdresse.getString("TEXT_WRONG_EXT"),
                        resCarnetAdresse.getString("TITLE_WRONG_EXT"),
                        JOptionPane.INFORMATION_MESSAGE);
                filePath = null;
                return false;
            }
        } catch (Exception ex) {
        }
        try {
            in = new DataInputStream(bfin);
            br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            if (carnetTableModel.getRowCount() > 0) {
                int n = JOptionPane
                        .showConfirmDialog(frame,
                                resCarnetAdresse.getString("TEXT_CLEAR_OLD_DATA"),
                                resCarnetAdresse.getString("TITLE_CLEAR_OLD_DATA"), JOptionPane.YES_NO_OPTION);

                if (n == JOptionPane.YES_OPTION) {
                    carnetTableModel.resetData();
                    searchTableModel.resetData();
                }
            }
            while ((strLine = br.readLine()) != null) {
                String[] str = strLine.split(",");
                Personne personne = new Personne();
                personne.setNom(str[carnetTableModel.COL_NOM].trim());
                personne.setNumeroDeTelephone(str[carnetTableModel.COL_NUMERO_DE_TELEPHONE].trim());
                personne.setAdresseDeTraivail(str[carnetTableModel.COL_ADRESSE_DE_TRAVAIL].trim());
                personne.setAdresseDeDomicile(str[carnetTableModel.COL_ADRESSE_DE_DOMICILE].trim());
                carnetTableModel.addCarte(personne);
            }
            frame.setTitle(resCarnetAdresse.getString("TITLE") + " - " + getFilename(filePath));
            if (carnetTableModel.getRowCount() > 0) {
                enableEditDeleteAction(true);
            }
            return true;
        } catch (Exception ex) {
        }
        return false;
    }
    /**
     * Travail avec fichier
     * Enregistrer carnet adresse en le fichier
     */
    public void saveAddressBook() {

        FileOutputStream bfout = null;
        try {
            bfout = new FileOutputStream(filePath);
        } catch (Exception ex) {
        }
        try {
            String content = "";
            List<Personne> pData = carnetTableModel.getData();

            for (int i = 0; i < pData.size(); i++) {
                content += pData.get(i).getNom() + " ,";
                content += pData.get(i).getNumeroDeTelephone() + " ,";
                content += pData.get(i).getAdresseDeTraivail() + " ,";
                content += pData.get(i).getAdresseDeDomicile() + " \n";
            }
            byte[] contentInBytes = content.getBytes();
            bfout.write(contentInBytes);
            frame.setTitle(resCarnetAdresse.getString("TITLE") + " - " + getFilename(filePath));
        } catch (Exception ex) {
        }
    }

    public void saveAsAddressBook() {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        chooser.setMultiSelectionEnabled(false);
        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        chooser.showSaveDialog(frame);

        FileOutputStream bfout = null;

        try {
            filePath = chooser.getSelectedFile().getPath();
        } catch (Exception ex) {
        }

        try {
            if (filePath.endsWith(".carnet")) {
                bfout = new FileOutputStream(filePath);
            } else {
                filePath += ".carnet";
                bfout = new FileOutputStream(filePath);
            }
        } catch (Exception ex) {
        }

        try {
            String content = "";
            List<Personne> pData = carnetTableModel.getData();

            for (int i = 0; i < pData.size(); i++) {
                content += pData.get(i).getNom() + " ,";
                content += pData.get(i).getNumeroDeTelephone() + " ,";
                content += pData.get(i).getAdresseDeTraivail() + " ,";
                content += pData.get(i).getAdresseDeDomicile() + " \n";
            }
            byte[] contentInBytes = content.getBytes();
            bfout.write(contentInBytes);
            frame.setTitle(resCarnetAdresse.getString("TITLE") + " - " + getFilename(filePath));
        } catch (Exception ex) {
        }
    }

    /**
     * Cette class pour controle tout les action dans GUI
     */
    private class TextHandler implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == menuItemAdd) {
                tabAllContact.setSelectedComponent(scrollPaneAll);
                btnAdd.setVisible(true);
                btnOK.setVisible(false);
                addFrame.setTitle(resCarnetAdresse.getString("MENU.Creer_carnet"));
                resetTextField();
                addFrame.setVisible(true);
            } else if (e.getSource() == menuItemEdit) {
                tabAllContact.setSelectedComponent(scrollPaneAll);
                if (carnetTable.getSelectedRow() != -1) {
                    showEditCarte(carnetTable.getSelectedRow());
                    addFrame.setTitle(resCarnetAdresse.getString("MENU.Modifier"));
                    addFrame.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(
                            addFrame,
                            resCarnetAdresse.getString("TEXT_CHOISIR"),
                            resCarnetAdresse.getString("TITLE_CHOISIR"),
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } else if (e.getSource() == menuItemDetele) {
                tabAllContact.setSelectedComponent(scrollPaneAll);
                if (carnetTable.getSelectedRow() != -1) {
                    int n = JOptionPane
                            .showConfirmDialog(frame,
                                    resCarnetAdresse.getString("TEXT_CONFIRMER_SUPPRIMER"),
                                    resCarnetAdresse.getString("TITLE_CONFIMRER"), JOptionPane.YES_NO_OPTION);
                    if (n == JOptionPane.YES_OPTION) {
                        carnetTableModel.deleteCarte(carnetTable.getSelectedRow());
                        if (carnetTableModel.getRowCount() == 0) {
                            enableEditDeleteAction(false);
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(
                            addFrame,
                            resCarnetAdresse.getString("TEXT_CHOISIR"),
                            resCarnetAdresse.getString("TITLE_CHOISIR"),
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } else if (e.getSource() == menuItemEditPerson) {
                tabAllContact.setSelectedComponent(scrollPaneAll);
                searchPersonFrame.setVisible(true);
                startSelection = 0;
                btnSearchEdit.setEnabled(false);
                btnSearchDetele.setEnabled(false);
            } else if (e.getSource() == menuItemOpen) {
                tabAllContact.setSelectedComponent(scrollPaneAll);
                openAddressBook();
            } else if (e.getSource() == menuItemSave) {
                tabAllContact.setSelectedComponent(scrollPaneAll);
                if (filePath != null) {
                    saveAddressBook();
                } else {
                    saveAsAddressBook();
                }
            } else if (e.getSource() == menuItemSaveAs) {
                tabAllContact.setSelectedComponent(scrollPaneAll);
                saveAsAddressBook();
            } else if (e.getSource() == menuItemExit) {
                System.exit(0);
            } else if (e.getSource() == menuItemSearch) {
                searchFrame.setVisible(true);
            } else if (e.getSource() == menuItemAbout) {
                JOptionPane.showMessageDialog(
                        addFrame,
                        resCarnetAdresse.getString("TEXT_ABOUT"),
                        resCarnetAdresse.getString("TITLE_ABOUT"),
                        JOptionPane.INFORMATION_MESSAGE);
            } else if (e.getSource() == btnAdd) {
                if (validateForm()) {
                    carnetTableModel.addCarte(getPersoneDataFromTextField());
                    JOptionPane.showMessageDialog(
                            addFrame,
                            resCarnetAdresse.getString("TEXT_SUCCES_CREER"),
                            resCarnetAdresse.getString("TITLE_SUCCES_CREER"),
                            JOptionPane.INFORMATION_MESSAGE);
                    resetTextField();
                    if (carnetTableModel.getRowCount() > 0) {
                        enableEditDeleteAction(true);
                    }
                }
            } else if (e.getSource() == btnOK) {
                if (validateForm()) {
                    carnetTableModel.editCarte(getPersoneDataFromTextField(), editedRow);
                    addFrame.setVisible(false);
                }
            } else if (e.getSource() == btnCancel) {
                addFrame.setVisible(false);
            } else if (e.getSource() == btnSearch) {
                searchFrame.setVisible(true);
                ArrayList<Personne> resultList = carnetTableModel.searchByName(txtSearchNom.getText());
                if (resultList.size() == 0) {
                    JOptionPane.showMessageDialog(
                            addFrame,
                            resCarnetAdresse.getString("TEXT_FIND_NOT_FOUND"),
                            resCarnetAdresse.getString("TITLE_FIND_NOT_FOUND"),
                            JOptionPane.INFORMATION_MESSAGE);
                } else {
                    searchTableModel.setData(resultList);
                    searchTableModel.fireTableDataChanged();
                    tabAllContact.addTab(resCarnetAdresse.getString("TAB_RESULT_SEARCH") + txtSearchNom.getText() + "'", scrollPaneSearch);
                    tabAllContact.setSelectedComponent(scrollPaneSearch);
                    searchFrame.setVisible(false);
                }
            } else if (e.getSource() == btnSearchCancel) {
                searchFrame.setVisible(false);
            } else if (e.getSource() == btnSearchPerson) {
                for (int i = startSelection; i < carnetTableModel.getRowCount(); i++) {
                    if (carnetTableModel.getData().get(i).getNom().toLowerCase().indexOf(txtSearchPersonNom.getText().toLowerCase()) != -1) {
                        carnetTable.setRowSelectionInterval(i, i);
                        startSelection = i + 1;
                        btnSearchEdit.setEnabled(true);
                        btnSearchDetele.setEnabled(true);
                        if (startSelection >= carnetTableModel.getRowCount()) {
                            startSelection = 0;
                        }
                        break;
                    }
                }
            } else if (e.getSource() == btnSearchEdit) {
                searchPersonFrame.setVisible(false);
                showEditCarte(carnetTable.getSelectedRow());
                addFrame.setTitle(resCarnetAdresse.getString("MENU.Modifier_carnet"));
                addFrame.setVisible(true);
            } else if (e.getSource() == btnSearchDetele) {
                int n = JOptionPane
                        .showConfirmDialog(frame,
                                resCarnetAdresse.getString("TEXT_CONFIRMER_SUPPRIMER"),
                                resCarnetAdresse.getString("TITLE_CONFIMRER"), JOptionPane.YES_NO_OPTION);

                if (n == JOptionPane.YES_OPTION) {
                    carnetTableModel.deleteCarte(carnetTable.getSelectedRow());
                    if (startSelection > 0) startSelection--;
                    if (carnetTableModel.getRowCount() == 0) {
                        enableEditDeleteAction(false);
                    }
                    for (int i = startSelection; i < carnetTableModel.getRowCount(); i++) {
                        if (carnetTableModel.getData().get(i).getNom().toLowerCase().indexOf(txtSearchPersonNom.getText().toLowerCase()) != -1) {
                            carnetTable.setRowSelectionInterval(i, i);
                            startSelection = i + 1;
                            btnSearchEdit.setEnabled(true);
                            btnSearchDetele.setEnabled(true);
                            if (startSelection >= carnetTableModel.getRowCount()) {
                                startSelection = 0;
                            }
                            break;
                        }
                    }
                    searchPersonFrame.setVisible(true);
                }
            }
        }
    }
}
